<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/16
 * Time: 14:45
 */

namespace App\Jobs;


use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Common as helper;

class MakeCollection extends Job
{
    protected $tender_id,$user_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tender_id,$user_id)
    {
        $this->tender_id = $tender_id;
        $this->user_id = $user_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 获取投资信息
        $tender = DB::table('borrow_tender')->where('id', $this->tender_id)->first();
        if(!$tender){
            exit("投资数据错误");
        }
        // 获取标的信息
        $borrow = DB::table('borrow')->where('id',$tender->borrow_id)->first();
        if(!$borrow){
            exit("标的数据错误");
        }
        // 查询当前投资下是否生成了足够的回款信息
        $is_make = false;
        $collections = DB::table('borrow_collection')->where('tender_id',$this->tender_id)->count();
        if($collections == 0){// 尚未生成回款信息
            $is_make = true;
        }

        if($borrow->style == 0){ // 一次性还本付息
            // 一次性还款每笔投资只生成一个回款信息
            if($collections == 1){
                exit("回款已生成");
            }
            // 如果一次性还款生成多笔回款信息，则生成错误，需要删掉重新生成
            if($collections > 1){
                // 删除原有的
                DB::table('borrow_collection')->where('tender_id',$this->tender_id)->delete();
                $is_make = true;
            }
            if($is_make){
                $res = $this->interest_once($borrow,$tender);
            }
        }else if($borrow->style == 1){ // 按月付息到期还本

            if($collections == $borrow->time_limit){// 回款信息等于借款月
                exit("回款已生成");
            }
            // 生成大于分期数量，或者生成了部分信息，都要删掉重新开始；
            if($collections > $borrow->time_limit || ($collections < $borrow->time_limit && $collections > 0)){
                // 删除原有的
                DB::table('borrow_collection')->where('tender_id',$this->tender_id)->delete();
                $is_make = true;
            }
            if($is_make){
                $res = $this->interest_month($borrow,$tender);
            }
        }
        // 执行入库操作
        if($res){
            foreach($borrow->results as $key => $value){
                $collection_data = [
                    'tender_id' => $this->tender_id,
                    'user_id' => $this->user_id,
                    'borrow_id' => $tender->borrow_id,
                    'trade_no' => helper::create_hf_no(),
                    'order_number' => $key,
                    'status' => 1,
                    'repay_account' => $value['repayment_account'],
                    'capital' => $value['capital'],
                    'interest' => $value['interest'],
                    'repay_time' => $value['repayment_time'],
                    'creater' => $this->user_id,
                    'create_time' => time(),
                    'updater' => $this->user_id,
                    'update_time' => time(),
                ];
                $coll_id = DB::table('borrow_collection')->insertGetId($collection_data);
                helper::write_log('make_collection_'.date('Y-m').".log",$coll_id."-".date('Y-m-d H:i:s')."\n");
            }

        }
        echo "ok";
    }
    /**
     * 一次性还款
     *
     * @return boolean
     */
    private function interest_once(&$borrow,&$tender)
    {
        $borrow->results = array();

        if($borrow->style != 0)
        {
            return false;
        }

        if(empty($tender->money))
        {
            return false;
        }

        if(empty($borrow->apr))
        {
            return false;
        }

        if(empty($borrow->time_limit))
        {
            return false;
        }

        if(empty($borrow->time_start))
        {
            $this->time_start = time();
        }

        if($borrow -> cycle_unit == 1){
            // 日
            $interest = round($tender->money * $borrow->apr/365*$borrow->time_limit, 2);//利息等于应还金额乘季利率
        }elseif($borrow -> cycle_unit == 3){
            // 月
            $interest = round($tender->account * $borrow->apr/12*$borrow->time_limit, 2);//利息等于应还金额乘月利率
        }
        $capital = round($tender->money, 2);//本金利息都一样
        for($i = 1; $i <= 1; $i++)
        {
            $borrow->results[$i]['repayment_account'] = $interest + $capital;
            $borrow->results[$i]['repayment_time'] = $borrow->time_limit*86400 + $borrow->time_start;
            $borrow->results[$i]['interest'] = $interest;
            $borrow->results[$i]['capital'] = $capital;
        }
        return true;
    }

    /**
     * 到期还本，按月付息
     *
     * @return boolean
     */
    private function interest_month(&$borrow,&$tender)
    {
        $borrow->results = array();

        if($borrow->style != 1)
        {
            return false;
        }

        if(empty($tender->money))
        {
            return false;
        }

        if(empty($borrow->apr))
        {
            return false;
        }

        if(empty($borrow->time_limit))
        {
            return false;
        }

        if(empty($borrow->time_start))
        {
            $borrow->time_start = time();
        }

        //月利率
        $month_apr = round($borrow->apr/12,9);
        $interest = round($tender->money * $month_apr, 2);//利息等于应还金额乘月利率

        // 总利息 投资金额*收益率*出借期限/12
        $interest_total = $tender->money*$borrow->apr*$borrow->time_limit/12;

        $capital = 0;
        $interest_sum = 0;
        for($i = 1; $i <= $borrow->time_limit; $i++)
        {
            if ($i == $borrow->time_limit)
            {
                $interest = $interest_total - $interest_sum;// 最后一个月的利息，等于总利息-之前的所有利息
                $capital = round($tender->money, 2);//本金只在最后一个月还，本金等于借入金额
            }else{
                $interest_sum += $interest;
            }

            $borrow->results[$i]['repayment_account'] = $interest + $capital;
            $borrow->results[$i]['repayment_time'] = helper::time_month_creater($i, $borrow->time_start);
            $borrow->results[$i]['interest'] = $interest;
            $borrow->results[$i]['capital'] = $capital;
        }

        return true;
    }
}